package com.ruoyi.user.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.dddetails.domain.DdDetails;
import com.ruoyi.dddetails.mapper.DdDetailsMapper;
import com.ruoyi.departmentdisease.domain.DepartmentDisease;
import com.ruoyi.departmentdisease.mapper.DepartmentDiseaseMapper;
import com.ruoyi.descriptionrule.domain.DescriptionRule;
import com.ruoyi.descriptionrule.mapper.DescriptionRuleMapper;
import com.ruoyi.disease.domain.Disease;
import com.ruoyi.disease.mapper.DiseaseMapper;
import com.ruoyi.doctordisease.mapper.DoctorDiseaseMapper;
import com.ruoyi.doctorlibrary.mapper.DoctorLibraryMapper;
import com.ruoyi.finance.domain.Finance;
import com.ruoyi.finance.domain.vo.FinanceVO;
import com.ruoyi.finance.mapper.FinanceMapper;
import com.ruoyi.income.domain.Income;
import com.ruoyi.income.mapper.IncomeMapper;
import com.ruoyi.order.service.IOrderService;
import com.ruoyi.user.domain.vo.*;
import com.ruoyi.userdisease.domain.UserDisease;
import com.ruoyi.userdisease.mapper.UserDiseaseMapper;
import com.ruoyi.withdrawaltable.domain.WithdrawalTable;
import com.ruoyi.withdrawaltable.mapper.WithdrawalTableMapper;
import com.ruoyi.workexperience.domain.WorkExperience;
import com.ruoyi.workexperience.mapper.WorkExperienceMapper;
import com.ruoyi.wx.utils.NameUtil;
import com.ruoyi.wx.utils.Sample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;

import static com.aliyun.teautil.Common.toJSONString;

import javax.servlet.http.HttpServletRequest;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-03
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DdDetailsMapper ddDetailsMapper;

    @Autowired
    private IncomeMapper incomeMapper;

    @Autowired
    private UserDiseaseMapper userDiseaseMapper;

    @Autowired
    private DiseaseMapper diseaseMapper;

    @Autowired
    private DoctorLibraryMapper doctorLibraryMapper;

    @Autowired
    private WithdrawalTableMapper withdrawalTableMapper;

    @Autowired
    private DepartmentDiseaseMapper departmentDiseaseMapper;

    @Autowired
    private DoctorDiseaseMapper doctorDiseaseMapper;

    @Autowired
    private FinanceMapper financeMapper;

    @Autowired
    private DescriptionRuleMapper descriptionRuleMapper;
    @Autowired
    private IOrderService orderService;

    @Autowired
    private WorkExperienceMapper workExperienceMapper;


    @Value("${ruoyi.avatar}")
    private String avatar;

    @Autowired
    private Sample sample;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public UserVO selectUserById(Long id) {
        UserVO userVO = new UserVO();
        User user = userMapper.selectUserById(id);
        Long isExpert = user.getIsExpert();
        BeanUtils.copyProperties(user, userVO);
        DdDetails ddDetails = new DdDetails();
        ddDetails.setId(user.getUserId());
        Income income = new Income();
        income.setUserId(user.getUserId());
        if (isExpert == 1) {
            List<DdDetails> ddDetailsList = ddDetailsMapper.selectDdDetailsList(ddDetails);
            userVO.setDdDetailsList(ddDetailsList);
        } else {
            List<DdDetails> ddDetailsList = ddDetailsMapper.selectDdDetailsList(ddDetails);
            userVO.setDdDetailsList(ddDetailsList);
            List<Income> incomeList = incomeMapper.selectIncomeList(income);
            userVO.setIncomeList(incomeList);
            User user1 = new User();
            user1.setInviterId(user.getInvitationCode());
            user1.setIsExpert(1L);
            List<User> userByInviterId = getUserByInviterId(user1);
            List<IUser> iUsers = new ArrayList<>();
            if (userByInviterId != null && !userByInviterId.isEmpty()) {
                for (User user2 : userByInviterId) {
                    IUser iUser = new IUser();
                    BeanUtils.copyProperties(user2, iUser);
                    iUsers.add(iUser);
                }
            }
            user1.setIsExpert(0L);
            List<User> expertList = getUserByInviterId(user1);
            ArrayList<Expert> experts = new ArrayList<>();
            if (expertList != null && !expertList.isEmpty()) {
                for (User user2 : expertList) {
                    Expert expert = new Expert();
                    BeanUtils.copyProperties(user2, expert);
                    experts.add(expert);
                }
            }
            userVO.setExpertList(experts);
            // 查询专家对应的病种
            UserDisease userDisease = new UserDisease();
            userDisease.setUserId(user.getUserId());
            List<UserDisease> userDiseases = userDiseaseMapper.selectUserDiseaseList(userDisease);
            ArrayList<Disease> diseases = new ArrayList<>();
            for (UserDisease disease : userDiseases) {
                Disease disease1 = diseaseMapper.selectDiseaseByDiseaseId(disease.getDiseaseId());
                diseases.add(disease1);
            }
            userVO.setDiseaseList(diseases);
            WorkExperience workExperience = new WorkExperience();
            workExperience.setUserId(user.getUserId());
            List<WorkExperience> workExperiences = workExperienceMapper.selectWorkExperienceList(workExperience);
            userVO.setWorkExperiences(workExperiences);
            userVO.setIUserList(iUsers);
        }
        return userVO;
    }

    @Override
    public UserVO selectUserByUserId(String userId) {
        UserVO userVO = new UserVO();
        User user = userMapper.selectUserByUserId(userId);
        String workExperience = user.getWorkExperience();
        if (workExperience != null) {
            String[] split = workExperience.split(",");
            List<String> workExperienceList = new ArrayList<>();
            workExperienceList.addAll(Arrays.asList(split));
            userVO.setWorkExperienceList(workExperienceList);
        }
        Long isExpert = user.getIsExpert();
        BeanUtils.copyProperties(user, userVO);
        DdDetails ddDetails = new DdDetails();
        ddDetails.setId(user.getUserId());
        Income income = new Income();
        income.setUserId(user.getUserId());
        if (isExpert == 1) {
            List<DdDetails> ddDetailsList = ddDetailsMapper.selectDdDetailsList(ddDetails);
            userVO.setDdDetailsList(ddDetailsList);
        } else {
            List<DdDetails> ddDetailsList = ddDetailsMapper.selectDdDetailsList(ddDetails);
            userVO.setDdDetailsList(ddDetailsList);
            List<Income> incomeList = incomeMapper.selectIncomeList(income);
            userVO.setIncomeList(incomeList);
            WithdrawalTable withdrawalTable = new WithdrawalTable();
            withdrawalTable.setUserId(user.getUserId());
            List<WithdrawalTable> withdrawalTables = withdrawalTableMapper.selectWithdrawalTableList(withdrawalTable);
            userVO.setWithdrawalTableList(withdrawalTables);
            User user1 = new User();
            user1.setInviterId(user.getInvitationCode());
            user1.setIsExpert(1L);
            List<User> userByInviterId = getUserByInviterId(user1);
            List<IUser> iUsers = new ArrayList<>();
            if (userByInviterId != null && !userByInviterId.isEmpty()) {
                for (User user2 : userByInviterId) {
                    IUser iUser = new IUser();
                    BeanUtils.copyProperties(user2, iUser);
                    iUsers.add(iUser);
                }
            }
            user1.setIsExpert(0L);
            List<User> expertList = getUserByInviterId(user1);
            ArrayList<Expert> experts = new ArrayList<>();
            if (expertList != null && !expertList.isEmpty()) {
                for (User user2 : expertList) {
                    Expert expert = new Expert();
                    BeanUtils.copyProperties(user2, expert);
                    experts.add(expert);
                }
            }
            userVO.setExpertList(experts);
            // 查询专家对应的病种
            UserDisease userDisease = new UserDisease();
            userDisease.setUserId(user.getUserId());
            List<UserDisease> userDiseases = userDiseaseMapper.selectUserDiseaseList(userDisease);
            ArrayList<Disease> diseases = new ArrayList<>();
            for (UserDisease disease : userDiseases) {
                Disease disease1 = diseaseMapper.selectDiseaseByDiseaseId(disease.getDiseaseId());
                DepartmentDisease departmentDisease = departmentDiseaseMapper.selectDepartmentDiseaseByDiseaseId(disease1.getDiseaseId());
                disease1.setDepartmentId(departmentDisease.getDepartmentId());
                diseases.add(disease1);
            }
            userVO.setDiseaseList(diseases);
            WorkExperience workExperience1 = new WorkExperience();
            workExperience1.setUserId(user.getUserId());
            List<WorkExperience> workExperiences = workExperienceMapper.selectWorkExperienceList(workExperience1);
            userVO.setWorkExperiences(workExperiences);
            userVO.setIUserList(iUsers);
        }
        return userVO;
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param user 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<UserVO> selectUserList(User user) {
        List<UserVO> userVOS = new ArrayList<>();
        List<User> users = userMapper.selectUserList(user);
        for (User user1 : users) {
            Long isExpert = user1.getIsExpert();
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user1, userVO);
            DdDetails ddDetails = new DdDetails();
            ddDetails.setId(user1.getUserId());
            Income income = new Income();
            income.setUserId(user1.getUserId());
            // 用户
            if (isExpert == 1) {
                List<DdDetails> ddDetailsList = ddDetailsMapper.selectDdDetailsList(ddDetails);
                userVO.setDdDetailsList(ddDetailsList);
            } else {
                List<DdDetails> ddDetailsList = ddDetailsMapper.selectDdDetailsList(ddDetails);
                userVO.setDdDetailsList(ddDetailsList);
                List<Income> incomeList = incomeMapper.selectIncomeList(income);
                userVO.setIncomeList(incomeList);
            }
            userVOS.add(userVO);
        }
        return userVOS;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param uservo 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(UserVO uservo) {
        User user = new User();
//        List<Long> diseaseIds = uservo.getDiseaseIds();
        user.setUsername(uservo.getUsername());
        User user2 = userMapper.selectUserByUsername(user);
        if (user2 != null) {
            return 0;
        } else {
            String nickName = NameUtil.getName();
            user.setIsExpert(0L);
            // 查询当前最大 id
            Integer maxId = userMapper.selectMaxId();
            int nextId = maxId == null ? 1 : maxId + 1;
            // 前补零，生成 6 位 user_id
            String userId = String.format("%06d", nextId);
            user.setUserId(userId);
            user.setInvitationCode(userId);
            user.setPhone(uservo.getUsername());
            user.setUsername(uservo.getUsername() + "__expert");
            String password = SecurityUtils.encryptPassword(uservo.getPassword());
            user.setPassword(password);
            user.setCreateTime(DateUtils.getNowDate());
            // 注册叮豆
            user.setDdTotalNumber(BigDecimal.valueOf(20));
            user.setCumulativeDd(BigDecimal.valueOf(20));
            // 专家状态
            user.setUserStatus("0");
            user.setTotalAmount(BigDecimal.valueOf(0));
            user.setFreezeAmount(BigDecimal.valueOf(0));
            user.setWithdrawableAmount(BigDecimal.valueOf(0));
            user.setNickname(nickName);
            user.setIsExpert(0L);
            user.setQualificationsInt(0);
            // 审核状态
//        user.setProcessStatus("2");
            int insertUser = userMapper.insertUser(user);
//        if (insertUser > 0) {
//            for (Long diseaseId : diseaseIds) {
//                UserDisease userDisease = new UserDisease();
//                userDisease.setUserId(userId);
//                userDisease.setDiseaseId(diseaseId);
//                userDiseaseMapper.insertUserDisease(userDisease);
//            }
//        }
            DdDetails ddDetails = new DdDetails();
            ddDetails.setId(userId);
            ddDetails.setCreateTime(DateUtils.getNowDate());
            ddDetails.setSource("注册收益");
            ddDetails.setDetails("+20.00");
            ddDetailsMapper.insertDdDetails(ddDetails);
            if (uservo.getInviterId() != null) {
                User user1 = userMapper.selectUserByUserId(uservo.getInviterId());
                if (user1 != null) {
                    BigDecimal add = user1.getDdTotalNumber().add(BigDecimal.valueOf(5));
                    user1.setDdTotalNumber(add);
                    user1.setCumulativeDd(user1.getCumulativeDd().add(BigDecimal.valueOf(5)));
                    userMapper.updateUser(user1);
                    DdDetails ddDetails1 = new DdDetails();
                    ddDetails1.setId(user1.getUserId());
                    ddDetails1.setCreateTime(DateUtils.getNowDate());
                    ddDetails1.setSource("邀请收益");
                    ddDetails1.setDetails("+5.00");
                    ddDetailsMapper.insertDdDetails(ddDetails1);
                }
            }
            return insertUser;
        }
    }

    @Override
    @Transactional
    public int insertExpertUser(UserVO uservo) {
        User user1 = userMapper.selectUserByUserId(uservo.getUserId());
        Integer qualificationsInt = user1.getQualificationsInt();
        if (qualificationsInt < 2) {
            User user = new User();
            BeanUtils.copyProperties(uservo, user);
            List<Long> diseaseIds = uservo.getDiseaseIds();
            // 专家状态
            user.setUserStatus("0");
            // 审核状态
            user.setProcessStatus("2");
            user.setIsExpert(0L);
            user.setQualificationsInt(qualificationsInt + 1);
            String idCard = user.getIdCard();
            if (idCard != null && idCard.length() != 18 && !idCard.isEmpty()) {
                int genderCode = Integer.parseInt(idCard.substring(16, 17));
                String gender = genderCode % 2 == 0 ? "女" : "男";
                user.setGender(gender);
                String birthStr = idCard.substring(6, 14); // 出生年月日 yyyyMMdd
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                LocalDate birthDate = LocalDate.parse(birthStr, formatter);
                LocalDate now = LocalDate.now();
                int years = Period.between(birthDate, now).getYears();
                user.setAge((long) years);
            }
            int insertUser = userMapper.updateUser(user);
            userDiseaseMapper.deleteDoctorDiseaseByUserId(user.getUserId());
            for (Long diseaseId : diseaseIds) {
                UserDisease userDisease = new UserDisease();
                userDisease.setUserId(user.getUserId());
                userDisease.setDiseaseId(diseaseId);
                userDiseaseMapper.insertUserDisease(userDisease);
            }
            workExperienceMapper.deleteWorkExperienceByUserId(user.getUserId());
            List<WorkExperience> workExperiences = uservo.getWorkExperiences();
            if (!workExperiences.isEmpty()) {
                for (WorkExperience workExperience : workExperiences) {
                    workExperience.setUserId(user.getUserId());
                    workExperienceMapper.insertWorkExperience(workExperience);
                }
            }
            return insertUser;
        } else {
            return 0;
        }
    }

//    public Long generateInviteCode() {
//        Random random = new Random();
//        // 生成100000到999999之间的随机数，并返回 Long 类型
//        return 100000L + random.nextInt(900000); // 直接转换为 Long 类型
//    }


    /**
     * 修改【请填写功能名称】
     *
     * @param user 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] ids) {
        int i = 0;
        for (Long id : ids) {
            User user = userMapper.selectUserById(id);
            i = userMapper.deleteUserById(id);
            ddDetailsMapper.deleteDdDetailsById(user.getUserId());
            userDiseaseMapper.deleteUserDiseaseByUserId(user.getUserId());
            incomeMapper.deleteIncomeById(user.getUserId());
            doctorLibraryMapper.deleteDoctorLibraryByUserId(user.getUserId());
        }
        return i;
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long id) {
        User user = userMapper.selectUserById(id);
        userMapper.deleteUserById(id);
        ddDetailsMapper.deleteDdDetailsById(user.getUserId());
        userDiseaseMapper.deleteUserDiseaseByUserId(user.getUserId());
        return incomeMapper.deleteIncomeById(user.getUserId());
    }

    @Override
    public List<User> getUserByInviterId(User user) {
        return userMapper.selectUserByInviterId(user);
    }

    @Override
    public int updatePwd(User user) {
        String password = SecurityUtils.encryptPassword(user.getPassword());
        user.setPassword(password);
        return userMapper.updatePwd(user);
    }

    @Override
    public int updateProcessStatus(UserVO userVO) {
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        String processStatus = user.getProcessStatus();
        if ("1".equals(processStatus)) {
            user.setQualificationsInt(user.getQualificationsInt() - 1);
            orderService.pushMessage(user.getUserId(), "驳回");
        } else {
            orderService.pushMessage(user.getUserId(), "通过");
        }
        return userMapper.updateProcessStatus(user);
    }

    /**
     * 专家注册
     *
     * @param expertLoginVO
     * @return
     */
    @Override
    @Transactional
    public String register(ExpertLoginVO expertLoginVO) {
        User user = new User();
        user.setUsername(expertLoginVO.getUsername());
        user.setPassword(expertLoginVO.getPassword());
        String result = null;
        // 先查询是否已经注册
        user.setIsExpert(0L);
        User user1 = userMapper.selectUserByUsername(user);
        if (user1 != null) {
            result = "账号已注册";
        } else {
            String nickName = NameUtil.getName();
            // 查询当前最大 id
            Integer maxId = userMapper.selectMaxId();
            int nextId = maxId == null ? 1 : maxId + 1;
            // 前补零，生成 6 位 user_id
            String userId = String.format("%06d", nextId);
            user.setUserId(userId);
            user.setInvitationCode(userId);
            String password = SecurityUtils.encryptPassword(user.getPassword());
            user.setPassword(password);
            user.setCreateTime(DateUtils.getNowDate());
            // 注册叮豆
            user.setDdTotalNumber(BigDecimal.valueOf(20));
            user.setCumulativeDd(BigDecimal.valueOf(20));
            // 专家状态
            user.setUserStatus("0");
            user.setNickname(nickName);
            user.setIsExpert(0L);
            userMapper.insertUser(user);
            DdDetails ddDetails = new DdDetails();
            ddDetails.setId(userId);
            ddDetails.setCreateTime(DateUtils.getNowDate());
            ddDetails.setSource("注册收益");
            ddDetails.setDetails("+20.00");
            ddDetailsMapper.insertDdDetails(ddDetails);
            String inviterId = user.getInviterId();
            if (inviterId != null && !"".equals(inviterId)) {
                DdDetails ddDetails1 = new DdDetails();
                ddDetails1.setId(inviterId);
                ddDetails1.setSource("邀请收益");
                ddDetails1.setDetails("+5.00");
                ddDetails1.setCreateTime(new Date());
                ddDetailsMapper.insertDdDetails(ddDetails1);
                User user2 = userMapper.selectUserByUserId(inviterId);
                BigDecimal ddTotalNumber = user2.getDdTotalNumber();
                user2.setDdTotalNumber(ddTotalNumber.add(BigDecimal.valueOf(5)));
                user2.setDdTotalNumber(user2.getCumulativeDd().add(BigDecimal.valueOf(5)));
                userMapper.updateUser(user2);
            }
            result = "注册成功";
        }
        return result;
    }

    /**
     * 修改用户头像
     *
     * @param userId
     * @param file
     * @param request
     * @return
     */
    @Override
    public AjaxResult updateUserAvatar(String userId, MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return AjaxResult.error("请选择文件");
        }
        String fileUrl;
        try {
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            fileUrl = FileUploadUtils.upload(filePath, file);

            User user = new User();
            user.setUserId(userId);
            user.setImageAddress(fileUrl);
            // 更新数据库
            userMapper.updateUser(user);

        } catch (IOException e) {
            log.error("头像上传失败", e);
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
        return AjaxResult.success("上传成功");
    }

    /**
     * 查询专家收益
     *
     * @param loginUser
     * @return
     */
    @Override
    public IncomeVO selectUserIncome(User loginUser) {
        IncomeVO incomeVO = new IncomeVO();
        List<Income> incomeList = incomeMapper.selectIncomeByIncomeDetails(loginUser.getUserId());
        WithdrawalTable withdrawalTable = new WithdrawalTable();
        withdrawalTable.setUserId(loginUser.getUserId());
        List<WithdrawalTable> withdrawalTables = withdrawalTableMapper.selectWithdrawalTableList(withdrawalTable);
        User user = userMapper.selectUserByUserId(loginUser.getUserId());
        incomeVO.setUser(user);
        incomeVO.setIncome(incomeList);
        incomeVO.setWithdrawalIncome(withdrawalTables);
        return incomeVO;
    }

    /**
     * 修改专家信息
     *
     * @param userVO
     * @return
     */
    @Transactional
    @Override
    public AjaxResult updateExpert(UserVO userVO) {
        User user = userMapper.selectUserByUserId(userVO.getUserId());
        String phone = user.getPhone();
        String phone1 = userVO.getPhone();
        if (!phone.equals(phone1) && phone1 != null) {
            String username = user.getPhone();
            String code = userVO.getCode();
            // 获取 RedisCache Bean
            RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
            String redisKey = "sms:code:" + username;

            // 从 Redis 取出验证码
            String redisCode = redisCache.getCacheObject(redisKey);
            if (redisCode == null) {
                return AjaxResult.error("验证码已过期，请重新获取");
            } else if (!redisCode.equals(code)) {
                return AjaxResult.error("验证码错误");
            } else {
                user.setPhone(phone1);
                user.setUsername(phone1 + "__expert");
            }
        }
        String inviterId = user.getInviterId();
        if (inviterId == null || "".equals(inviterId)) {
            User user2 = userMapper.selectUserByUserId(userVO.getInviterId());
            if (user2 != null) {
                BigDecimal ddTotalNumber = user2.getDdTotalNumber();
                user2.setDdTotalNumber(ddTotalNumber.add(BigDecimal.valueOf(5)));
                user2.setCumulativeDd(user2.getCumulativeDd().add(BigDecimal.valueOf(5)));
                userMapper.updateUser(user2);
                DdDetails ddDetails = new DdDetails();
                ddDetails.setId(user2.getUserId());
                ddDetails.setSource("邀请收益");
                ddDetails.setDetails("+5.00");
                ddDetails.setCreateTime(DateUtils.getNowDate());
                ddDetailsMapper.insertDdDetails(ddDetails);
                user.setInviterId(user2.getUserId());
            } else if (userVO.getDiseaseIds() != null) {
                userDiseaseMapper.deleteUserDiseaseByUserId(user.getUserId());
                List<Long> diseaseIds = userVO.getDiseaseIds();
                for (Long diseaseId : diseaseIds) {
                    UserDisease userDisease = new UserDisease();
                    userDisease.setUserId(user.getUserId());
                    userDisease.setDiseaseId(diseaseId);
                    userDiseaseMapper.insertUserDisease(userDisease);
                }
            }
        }
        userMapper.updateUser(user);
        return AjaxResult.success("修改完成");
    }

    @Override
    public List<String> selectUserCity(User loginUser) {
        User user = userMapper.selectUserByUserId(loginUser.getUserId());
        String address = user.getAddress();
        if (address != null && !"".equals(address)) {
            String[] split = address.split(",");
            return Arrays.asList(split);
        }
        return Collections.emptyList();
    }

    /**
     * 获取手机验证码
     *
     * @param expertLoginVO
     */
    @Override
    public void getPhoneCode(ExpertLoginVO expertLoginVO) {
        String phone = expertLoginVO.getUsername();
        SendSmsResponse sendSmsResponse = null;
        String code = generateCode(6);
        if (phone != null && !"".equals(phone)) {
            try {
                // 初始化请求客户端
                Client client = sample.createClient();

                // 构造API请求对象，请替换请求参数值
                SendSmsRequest sendSmsRequest = new SendSmsRequest()
                        .setPhoneNumbers(phone)
                        .setSignName("武汉好医帮医药健康咨询服")
                        .setTemplateCode("SMS_323280356")
                        .setTemplateParam("{\"code\":\"" + code + "\"}"); // TemplateParam为序列化后的JSON字符串。

                // 获取响应对象
                sendSmsResponse = client.sendSms(sendSmsRequest);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        // 响应包含服务端响应的 body 和 headers
        System.out.println(toJSONString(sendSmsResponse));
        // 获取 RedisCache Bean
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);

        // 存验证码到 Redis，有效期 5 分钟
        String redisKey = "sms:code:" + phone;
        redisCache.setCacheObject(redisKey, code, 5, TimeUnit.MINUTES);
    }

    public static String generateCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10)); // 0-9
        }
        return code.toString();
    }

    /**
     * 查询专家病种列表
     *
     * @param loginUser
     * @return
     */
    @Override
    public List<UserDisease> selectExpertDisease(User loginUser) {
        UserDisease userDisease = new UserDisease();
        userDisease.setUserId(loginUser.getUserId());
        return userDiseaseMapper.selectUserDiseaseList(userDisease);
    }

    /**
     * 修改专家密码
     *
     * @param expertPwd
     * @return
     */
    @Override
    public String updateExpertPwd(ExpertPwd expertPwd) {
        String userId = expertPwd.getUserId();
        String password = SecurityUtils.encryptPassword(expertPwd.getPassword());
        User user = new User();
        user.setUserId(userId);
        user.setPassword(password);
        userMapper.updatePwd(user);
        return "修改成功";
    }

    /**
     * 提现申请
     *
     * @param withdrawalTable
     * @return
     */
    @Override
    @Transactional
    public AjaxResult withdrawal(WithdrawalTable withdrawalTable) {
        User user = userMapper.selectUserByUserId(withdrawalTable.getUserId());
        BigDecimal withdrawableAmount = user.getWithdrawableAmount();
        List<DescriptionRule> descriptionRules = descriptionRuleMapper.selectDescriptionRuleList(new DescriptionRule());
        if (!descriptionRules.isEmpty()) {
            DescriptionRule descriptionRule = descriptionRules.get(0);
            String ruleCommission = descriptionRule.getRuleCommission();
            // 先将字符串转换为 BigDecimal，并转换为小数比例
            BigDecimal commissionRate = new BigDecimal(ruleCommission).divide(new BigDecimal("100"));
            String ruleAmount = descriptionRule.getRuleAmount();
            BigDecimal ruleAmount1 = new BigDecimal(ruleAmount);
            if (withdrawableAmount.compareTo(ruleAmount1) >= 0) {
                BigDecimal totalAmount = withdrawalTable.getTotalAmount();
                if (withdrawableAmount.compareTo(totalAmount) >= 0) {
                    BigDecimal subtract = withdrawableAmount.subtract(totalAmount);
                    user.setWithdrawableAmount(subtract);
                    // 相乘计算结果
                    BigDecimal commissionAmount = totalAmount.multiply(commissionRate);
                    userMapper.updateUser(user);
                    withdrawalTable.setName(user.getName());
                    withdrawalTable.setPhone(user.getPhone());
                    withdrawalTable.setWithdrawalStatus("0");
                    withdrawalTable.setWithdrawalTime(DateUtils.getNowDate());
                    // 手续费
                    withdrawalTable.setCommission(commissionAmount);
                    BigDecimal actualAmount = totalAmount.subtract(commissionAmount);
                    // 实际收益
                    withdrawalTable.setActualAmount(actualAmount);
                    withdrawalTableMapper.insertWithdrawalTable(withdrawalTable);
                    return AjaxResult.success("提交成功, 等待审核");
                }else {
                    return AjaxResult.warn("提现金额不能大于可提现金额");
                }
            } else {
                return AjaxResult.warn("提现金额大于" + ruleAmount + "才可提现");
            }
        } else {
            return AjaxResult.error("提现规则未配置，请联系管理员");
        }
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @Override
    @Transactional
    public String updateUser1(User user) {
        String inviterId = user.getInviterId();
        if (inviterId != null) {
            User user2 = userMapper.selectUserByUserId(inviterId);
            if (user2 != null) {
                BigDecimal ddTotalNumber = user2.getDdTotalNumber();
                user2.setDdTotalNumber(ddTotalNumber.add(BigDecimal.valueOf(5)));
                user2.setCumulativeDd(user2.getCumulativeDd().add(BigDecimal.valueOf(5)));
                userMapper.updateUser(user2);
                DdDetails ddDetails = new DdDetails();
                ddDetails.setId(user2.getUserId());
                ddDetails.setSource("邀请收益");
                ddDetails.setDetails("+5.00");
                ddDetails.setCreateTime(DateUtils.getNowDate());
                ddDetailsMapper.insertDdDetails(ddDetails);
            }
        }
        userMapper.updateUser(user);
        return "修改成功";
    }

    /**
     * 后台数据统计
     *
     * @return
     */
    @Override
    public AjaxResult getStatisticsData() {
        FinanceVO financeVO = new FinanceVO();
        List<Finance> finances = financeMapper.selectFinances();
        // 总金额
        BigDecimal orderTotalAmount = BigDecimal.ZERO;
        if (finances != null) {
            for (Finance finance : finances) {
                orderTotalAmount = orderTotalAmount.add(finance.getDrawAmount());
            }
        }
        financeVO.setOrderTotalAmount(orderTotalAmount);
        List<Finance> finances1 = financeMapper.selectFinanceList(new Finance());
        if (finances1 != null) {
            // 总订单数
            String orderTotalNum = String.valueOf(finances1.size());
            financeVO.setOrderTotalNum(orderTotalNum);
        } else {
            financeVO.setOrderTotalNum("0");
        }
        // 今日收益
        List<Finance> finances2 = financeMapper.selectFinanceByDate();
        BigDecimal todayIncome = BigDecimal.ZERO;
        if (finances2 != null) {
            for (Finance finance : finances2) {
                todayIncome = todayIncome.add(finance.getDrawAmount());
            }
        }
        financeVO.setTodayIncome(todayIncome);
        // 今日订单数
        List<Finance> finances3 = financeMapper.selectFinanceByDate1();
        if (finances3 != null) {
            String todayOrderNum = String.valueOf(finances3.size());
            financeVO.setTodayOrderNum(todayOrderNum);
        } else {
            financeVO.setTodayOrderNum("0");
        }
        // 本月收益
        List<String> strings = splitMonthBy7Days(LocalDate.now());
        List<Finance> finances4 = financeMapper.selectThisMonth(strings.get(0), strings.get(1));
        BigDecimal monthIncome = BigDecimal.ZERO;
        if (finances4 != null) {
            for (Finance finance : finances4) {
                monthIncome = monthIncome.add(finance.getDrawAmount());
            }
        }
        financeVO.setMonthIncome(monthIncome);
        // 本月订单数
        List<Finance> finances5 = financeMapper.selectThisMonthNum(strings.get(0), strings.get(1));
        if (finances5 != null) {
            String monthOrderNum = String.valueOf(finances5.size());
            financeVO.setMonthOrderNum(monthOrderNum);
        } else {
            financeVO.setMonthOrderNum("0");
        }
        // 当前用户数
        User user = new User();
        user.setIsExpert(1L);
        List<User> users = userMapper.selectUserList(user);
        if (users != null) {
            financeVO.setUserTotalNum(String.valueOf(users.size()));
        } else {
            financeVO.setUserTotalNum("0");
        }
        // 当前专家数
        user.setIsExpert(0L);
        List<User> users1 = userMapper.selectUserList(user);
        if (users1 != null) {
            financeVO.setExpertTotalNum(String.valueOf(users1.size()));
        } else {
            financeVO.setExpertTotalNum("0");
        }
        List<String> last7Days = new ArrayList<>();
        LocalDate today = LocalDate.now();
        for (int i = 7; i >= 1; i--) {
            LocalDate date = today.minusDays(i);
            last7Days.add(date.toString()); // 格式: yyyy-MM-dd
        }
        Map<String, BigDecimal> stringBigDecimalHashMap = new LinkedHashMap<>();
        for (String last7Day : last7Days) {
            BigDecimal weekIncome = BigDecimal.ZERO;
            List<Finance> finances6 = financeMapper.selectFinanceByLast7Day(last7Day);
            if (finances6 != null) {
                for (Finance finance : finances6) {
                    weekIncome = weekIncome.add(finance.getDrawAmount());
                }
            }
            stringBigDecimalHashMap.put(last7Day, weekIncome);
        }
        financeVO.setWeekIncome(stringBigDecimalHashMap);
        List<User> users2 = userMapper.selectTop20UserBySum();
        ArrayList<Expert> experts = new ArrayList<>();
        for (User user1 : users2) {
            BigDecimal cumulativeDd = user1.getCumulativeDd();
            BigDecimal totalAmount = user1.getTotalAmount();
            Expert expert = new Expert();
            expert.setUserId(user1.getUserId());
            expert.setName(user1.getName());
            expert.setIncome(totalAmount.add(cumulativeDd));
            experts.add(expert);
        }
        financeVO.setExpertList(experts);
        return AjaxResult.success(financeVO);
    }

    @Override
    public User selectUserByServiceOpenId(String serviceOpenId) {
        return userMapper.selectUserByServiceOpenId(serviceOpenId);
    }

    @Override
    public void updateUserByServiceOpenId(String serviceOpenId, String userId) {
        userMapper.updateServiceOpenId(serviceOpenId, userId);
    }

    public List<String> splitMonthBy7Days(LocalDate month) {
        List<String> dateRanges = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 月初 & 月末
        LocalDate firstDay = month.withDayOfMonth(1);
        LocalDate lastDay = month.withDayOfMonth(month.lengthOfMonth());
        String format = firstDay.format(formatter);
        String format1 = lastDay.format(formatter);
        dateRanges.add(format);
        dateRanges.add(format1);
        return dateRanges;
    }
}
